package com.unitechs.trap.excel.webapi.service.impl.vbs;

import com.alibaba.fastjson.JSONObject;
import com.unitechs.trap.excel.service.IJsonTestService;
import com.unitechs.trap.excel.webapi.utils.HttpPostRequestUtils;
import com.unitechs.trap.excel.webapi.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;

import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class JsonTestServiceImpl implements IJsonTestService {

    @Override
    public List<JSONObject> writeJsonToExcel(String url, String devicesIp) {
        File file = new File(url);
        File[] files = file.listFiles();
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (File f : files) {
            if (!f.isDirectory() && f.getName().endsWith(".xls")) {
                try {
                    //创建工作簿对象
                    HSSFWorkbook xssfWorkbook = new HSSFWorkbook(new FileInputStream(f.getPath()));
                    //读取第1个工作表
                    HSSFSheet sheet = xssfWorkbook.getSheetAt(0);
                    //获取最后一行的num，即总行数。此处从0开始
                    int maxRow = sheet.getLastRowNum();
                    for (int row = 1; row <= maxRow; row++) {
                        if (sheet.getRow(row).getCell(0) == null) {
                            continue;
                        }
                        String xml = sheet.getRow(row).getCell(0).toString();
                        JSONObject trapJson = JsonUtil.getTrapJson(xml);
                        if (trapJson == null) {
                            continue;
                        }
                        if (sheet.getRow(row).getCell(1) == null) {
                            continue;
                        }

                        log.info("{}", trapJson);

                        String trapOid = sheet.getRow(row).getCell(1).toString();
                        trapJson.put("trapOid", trapOid);
                        trapJson.put("ResIP", devicesIp);


                        HSSFRow hssfRow = sheet.getRow(row);
                        if (hssfRow == null) {
                            hssfRow = sheet.createRow(row);
                        }

                        // 获取现有的单元格对象，如果不存在则创建新单元格
                        HSSFCell hssfCell = hssfRow.getCell(2);
                        if (hssfCell == null) {
                            hssfCell = hssfRow.createCell(2);
                        }
                        hssfCell.setCellValue(trapJson.toString().replace(",", ",\n").replace(",\n ", ", "));

                        FileOutputStream fos = new FileOutputStream(f);
                        xssfWorkbook.write(fos);
                        fos.flush();
                        fos.close();

                        jsonObjects.add(trapJson);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonObjects;
    }

    @Override
    public List<JSONObject> testTrapJson(String url, String devicesIp, String intface, String token) {
        List<JSONObject> jsonObjects = readJsonFromExcel(url, devicesIp, intface, token);

        return jsonObjects;
    }


    @Override
    public List<JSONObject> readJsonFromExcel(String url, String devicesIp, String intface, String token) {
        File file = new File(url);
        File[] files = file.listFiles();
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (File f : files) {
            if (!f.isDirectory() && f.getName().endsWith(".xls")) {
                try {
                    //创建工作簿对象
                    HSSFWorkbook xssfWorkbook = new HSSFWorkbook(new FileInputStream(f.getPath()));
                    //读取第1个工作表
                    HSSFSheet sheet = xssfWorkbook.getSheetAt(0);
                    //获取最后一行的num，即总行数。此处从0开始
                    int maxRow = sheet.getLastRowNum();
                    for (int row = 1; row <= maxRow; row++) {
                        if (sheet.getRow(row).getCell(0) == null) {
                            continue;
                        }
                        String xml = sheet.getRow(row).getCell(0).toString();
                        JSONObject trapJson = JsonUtil.getTrapJson(xml);
                        if (trapJson == null) {
                            continue;
                        }
                        if (sheet.getRow(row).getCell(1) == null) {
                            continue;
                        }


                        String trapOid = sheet.getRow(row).getCell(1).toString();
                        trapJson.put("trapOid", trapOid);
                        trapJson.put("ResIP", devicesIp);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("trapMessage", trapJson);


                        HSSFRow hssfRow = sheet.getRow(row);
                        if (hssfRow == null) {
                            hssfRow = sheet.createRow(row);
                        }

                        // 获取现有的单元格对象，如果不存在则创建新单元格
                        HSSFCell hssfCell = hssfRow.getCell(3);
                        if (hssfCell == null) {
                            hssfCell = hssfRow.createCell(3);
                        }
                        hssfCell.setCellValue(jsonObject.toString().replace(",", ",\n").replace(",\n ", ", "));


                        hssfRow = sheet.getRow(row);
                        if (hssfRow == null) {
                            hssfRow = sheet.createRow(row);
                        }
                        hssfCell = hssfRow.getCell(4);
                        if (hssfCell == null) {
                            hssfCell = hssfRow.createCell(4);
                        }


                        String response = HttpPostRequestUtils.trapHttpPostRequest(intface, token, jsonObject.toString()).toLowerCase();
                        response=response.replace("{","\n{").replace(",",",\n");
                        hssfCell.setCellValue(response);

                        hssfRow = sheet.getRow(row);
                        if (hssfRow == null) {
                            hssfRow = sheet.createRow(row);
                        }
                        hssfCell = hssfRow.getCell(5);
                        if (hssfCell == null) {
                            hssfCell = hssfRow.createCell(5);
                        }
                        String regexAlarm="\\{\"attributecode\":\"(?<attributecode>.*?)\",\n" +
                                "\"attributeescode\":\"(.*?)\",\n" +
                                "\"attributename\":\"(.*?)\",\n" +
                                "\"attributevalue\":\"(?<attributevalue>.*?)\",\n" +
                                "\"displayorder\":\"(.*?)\"},";

                        String alarmstatus = "";
                        String alarmclass = "";
                        String alarmclassname = "";
                        String alarmtypeid = "";
                        String alarmtype = "";
                        String severity = "";
                        String alarmlevelname = "";
                        String handlerulename = "";


                        Pattern pattern = Pattern.compile(regexAlarm);
                        Matcher matcher = pattern.matcher(response);

                        while (matcher.find()){
                            switch (matcher.group("attributecode")){
                                case "alarmstatus":alarmstatus=matcher.group("attributevalue");break;
                                case "alarmclass":alarmclass=matcher.group("attributevalue");break;
                                case "alarmclassname":alarmclassname=matcher.group("attributevalue");break;
                                case "alarmtypeid":alarmtypeid=matcher.group("attributevalue");break;
                                case "alarmtype": alarmtype=matcher.group("attributevalue");break;
                                case "severity": severity=matcher.group("attributevalue");break;
                                case "alarmlevelname":alarmlevelname=matcher.group("attributevalue");break;
                                case "handlerulename":handlerulename=matcher.group("attributevalue");break;
                            }

                        }



                        if (!alarmstatus.equals("0")&&(alarmstatus.equals("")
                                ||alarmclass.equals("")
                                ||alarmclassname.equals("")
                                ||alarmtypeid.equals("")
                                ||alarmtype.equals("")
                                ||severity.equals("")
                                ||alarmlevelname.equals(""))
                        ){
                            response="alarmstatus(告警状态 ):"+ alarmstatus+
                                    ";\nalarmclass(告警类别编码):" +alarmclass+
                                    ";\nalarmclassname(告警类别名称):" +alarmclassname+
                                    ";\nalarmtypeid(告警类型编码):" +alarmtypeid+
                                    ";\nalarmtype(告警类型名称):" +alarmtype+
                                    ";\nseverity(告警级别):" +severity+
                                    ";\nalarmlevelname(告警级别名称):" +alarmlevelname+
                                    ";\nhandlerulename(告警处理规则):" +handlerulename+
                                    ";\n匹配结果:失败";
                        }else {
                            response="alarmstatus(告警状态 ):"+ alarmstatus+
                                    ";\nalarmclass(告警类别编码):" +alarmclass+
                                    ";\nalarmclassname(告警类别名称):" +alarmclassname+
                                    ";\nalarmtypeid(告警类型编码):" +alarmtypeid+
                                    ";\nalarmtype(告警类型名称):" +alarmtype+
                                    ";\nseverity(告警级别):" +severity+
                                    ";\nalarmlevelname(告警级别名称):" +alarmlevelname+
                                    ";\nhandlerulename(告警处理规则):" +handlerulename+
                                    ";\n匹配结果:成功";
                        }
                        log.info("执行结果{}",response);
                        hssfCell.setCellValue(response);

                        FileOutputStream fos = new FileOutputStream(f);
                        xssfWorkbook.write(fos);
                        fos.flush();
                        fos.close();

                        JSONObject retJon=new JSONObject();
                        retJon.put("trap_oid",sheet.getRow(row).getCell(1).toString());
                        retJon.put("数据来自:",f.getName());
                        retJon.put("执行结果",response);
                        jsonObjects.add(retJon);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonObjects;
    }


}
